package com.aiti.lulian.controller.crm;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.CardInquiryDto;
import com.aiti.lulian.entity.LuLianEnterpriseUser;
import com.aiti.lulian.entity.ShowUserLog;
import com.aiti.lulian.entity.crad.BatchZj;
import com.aiti.lulian.entity.crad.CardInquiry;
import com.aiti.lulian.handler.InquiryEditFailedEvent;
import com.aiti.lulian.service.ICrmCardInquiryService;
import com.aiti.lulian.service.ILuLianEnterpriseUserService;
import com.aiti.lulian.service.IShowUserLogService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * Crm中的询盘功能
 *
 */
@EnableAsync
@RestController
@RequestMapping("/crm/inquiry")
public class CrmCardInquiryController extends WebController<CardInquiry> {

    private final ICrmCardInquiryService baseService;

    private final IShowUserLogService showUserLogService;

    private final ILuLianEnterpriseUserService enterpriseUserService;


    private ApplicationEventPublisher eventPublisher;


    public CrmCardInquiryController(ICrmCardInquiryService baseService,
                                    IShowUserLogService showUserLogService,
                                    ILuLianEnterpriseUserService enterpriseUserService,
                                    ApplicationEventPublisher eventPublisher) {
        this.baseService = baseService;
        this.showUserLogService = showUserLogService;
        this.enterpriseUserService = enterpriseUserService;
        this.eventPublisher = eventPublisher;
    }

    /**
     * 查询询盘列表
     * @param dto
     * @return
     */
    @GetMapping("/selectCrmInquiry")
    public Message selectCrmInquiry(CardInquiryDto dto) {
        String userId = findUserId();
        if(StringUtils.isBlank(userId)){
            userId = dto.getUserId();
        }
        if(StringUtils.isBlank(userId)){
            return Message.fail("没有找到当前用户Id");
        }
        Map<String, Object> resultMap = baseService.selectCrmInquiry(dto, userId);
        return Message.success(resultMap);
    }



    /**
     * 编辑
     * @param dto
     * @return
     */
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public Message editCrmInquiry(@RequestBody CardInquiry dto) {
        String userId = findUserId();
        try{
            if(StringUtils.isBlank(dto.getBaseId())){
                return Message.fail("没有找到Id");
            }

            CardInquiry byId = baseService.getById(dto.getBaseId());
            if(StringUtils.equals(byId.getFollowUpStatus(),"5")){
                return Message.fail("该询盘已经完成处理，不可编辑");
            }
            if(StringUtils.equals(byId.getFollowUpStatus(),"4")){
                return Message.fail("该询盘已关闭，不可编辑");
            }
            UpdateWrapper<CardInquiry> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("base_id",dto.getBaseId());
            updateWrapper.set(StringUtils.isNotBlank(dto.getLinkMan()),"link_man",dto.getLinkMan());
            updateWrapper.set(StringUtils.isNotBlank(dto.getLinkPhone()),"link_phone",dto.getLinkPhone());
            updateWrapper.set(StringUtils.isNotBlank(dto.getEnterpriseName()),"enterprise_name",dto.getEnterpriseName());
            updateWrapper.set(StringUtils.isNotBlank(dto.getFollowUpStatus()),"follow_up_status",dto.getFollowUpStatus());
            updateWrapper.set(StringUtils.isNotBlank(dto.getRemark()),"remark",dto.getRemark());
            updateWrapper.set(StringUtils.isNotBlank(dto.getDescInfo()),"desc_info",dto.getDescInfo());
            updateWrapper.set(StringUtils.isNotBlank(dto.getDeptId()),"dept_id",dto.getDeptId());
            updateWrapper.set(StringUtils.isNotBlank(dto.getDirector()),"director",dto.getDirector());
            updateWrapper.set(StringUtils.isNotBlank(dto.getDirector()),"crad_user_id",dto.getDirector());
            baseService.update(updateWrapper);
            logEditAction(userId,dto,"1","编辑询盘信息");
            return Message.success();
        }catch (Exception e){
            InquiryEditFailedEvent build = InquiryEditFailedEvent.builder()
                    .userId(userId)
                    .o(dto)
                    .modules("编辑询盘信息")
                    .status("2")
                    .errorInfo("错误信息：" + e.toString())
                    .build();
            eventPublisher.publishEvent(build);
            throw new RuntimeException("编辑失败", e);
        }
    }

    public void logEditAction(String userId, Object dto, String status,String modules) {
        ShowUserLog showUserLog = new ShowUserLog();
        showUserLog.setBaseId(IdUtil.simpleUUID());
        showUserLog.setUserId(userId);
        showUserLog.setBaseCreateTime(DateUtil.now());
        List<LuLianEnterpriseUser> list = enterpriseUserService.list(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
        if (list != null && list.size() > 0) {
            LuLianEnterpriseUser enterpriseUser = list.get(0);
            showUserLog.setEnterpriseId(enterpriseUser.getEnterpriseId());
        }
        showUserLog.setModules(modules);
        showUserLog.setStatus(status);
        showUserLog.setContents(JSONUtil.toJsonStr(dto));
        showUserLogService.save(showUserLog);
    }

    @PutMapping("/transferInquiry")
    @Transactional(rollbackFor = Exception.class)
    public Message transferInquiry(@RequestBody BatchZj cardInquiry){
        String userId = findUserId();
        if(StringUtils.isBlank(userId)){
            userId = cardInquiry.getUserId();
        }

        if(StringUtils.isBlank(userId)){
            return Message.fail("没有找到用户ID");
        }

        try{
            if((cardInquiry.getBaseIds() == null || cardInquiry.getBaseIds().isEmpty()) || StringUtils.isBlank(cardInquiry.getDirector())){
                return Message.fail("没有找到ID或转交人");
            }
            UpdateWrapper<CardInquiry> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("director",cardInquiry.getDirector());
            updateWrapper.set("crad_user_id",cardInquiry.getDirector());
            updateWrapper.set("dept_id",cardInquiry.getDeptId());
            updateWrapper.in("base_id",cardInquiry.getBaseIds());
            baseService.update(updateWrapper);
            logEditAction(userId,cardInquiry,"1","转交询盘信息");
            return Message.success();
        }catch (Exception e){
            InquiryEditFailedEvent build = InquiryEditFailedEvent.builder()
                    .userId(userId)
                    .modules("转交询盘信息")
                    .o(cardInquiry)
                    .status("2")
                    .errorInfo("错误信息：" + e.toString())
                    .build();
            eventPublisher.publishEvent(build);
            throw new RuntimeException("编辑失败", e);
        }
    }


    /**
     * 删除
     * @param dto
     * @return
     */
    @DeleteMapping
    @Transactional(rollbackFor = Exception.class)
    public Message deleteCrmCardInquiry(@RequestBody BatchZj dto){
        String userId = findUserId();
        try{
            if(dto.getBaseIds() == null || dto.getBaseIds().isEmpty()){
                return Message.fail("没有找到Id");
            }
            baseService.removeByIds(dto.getBaseIds());

            logEditAction(userId,dto,"1","删除询盘信息");
            return Message.success();
        }catch (Exception e){
            InquiryEditFailedEvent build = InquiryEditFailedEvent.builder()
                    .userId(userId)
                    .modules("删除询盘信息")
                    .o(dto)
                    .status("2")
                    .errorInfo("错误信息：" + e.toString())
                    .build();
            eventPublisher.publishEvent(build);
            throw new RuntimeException("编辑失败", e);
        }
    }

    /**
     * 详情
     * @param dto
     * @return
     */
    @GetMapping("/detail")
    public Message getCrmCardInquiry(CardInquiryDto dto){
        if(StringUtils.isBlank(dto.getBaseId())){
            return Message.fail("没有找到ID");
        }

        CardInquiry one = baseService.getCrmCardInquiry(dto);
        return Message.success(one);
    }

    /**
     * 查询CRM中询盘是否有编辑删除的权限
     * @return
     */
    @GetMapping("/queryEditRemovePre")
    public Message queryEditRemovePre(){
        String userId = findUserId();
        return baseService.queryEditRemovePre(userId);
    }
}
